import $ from 'jquery';
import {MessageBox,Notification} from 'element-ui';
export default {
    apiBaseUrl:'http://localhost:8080/',
    ajax:function (config) {
        var self = this;
        if((typeof config.auth === "undefined") || config.auth){
            if(!config.headers) config.headers = {};
            $.extend(config.headers,self.getAjaxAuthHeaders());
        }
        config.complete = function(xhr,ts){
            console.log(config.url);
            console.log(xhr);
            console.log(ts);
            if(xhr.status == 401){
                MessageBox.alert({
                    title:'请重新登录',
                    callback:function () {
                        localtion.href='/#/login';
                    }
                })
            }
            if(xhr.status == 500){
                if(xhr.responseJSON){
                    Notification.error({
                        title:xhr.responseJSON.error,
                        message:xhr.responseJSON.message
                    });
                }else{
                    top.location.href = '/#/500';
                }
            }
            if(xhr.status == 200){
                if(typeof xhr.responseJSON == 'boolean'){
                    if(xhr.responseJSON){
                        Notification.success('ok');
                    }else{
                        Notification.error('failed');
                    }
                }else if('status' in xhr.responseJSON && 'msg' in xhr.responseJSON){
                    if(xhr.responseJSON.status == 'OK'){
                        Notification.success(xhr.responseJSON.msg);
                    }else{
                        Notification.error(xhr.responseJSON.msg);
                    }
                }
            }
            if(xhr.status == 404){
                top.location.href = '/#/404';
            }
        }
        config.url = this.apiBaseUrl + config.url;
        $.ajax(config);
    },
    getAccountId:function () {
        return localStorage.getItem("loggedAccountId");
    },
    getAjaxAuthHeaders:function () {
        return {
            'CURRENT_USER_ID':localStorage.getItem("loggedAccountId"),
            'TOKEN':localStorage.getItem("token")
        };
    },
    restful:function (type,sourceUrl,data,callback) {
        this.ajax({
            url:sourceUrl,
            type:type,
            data:data,
            success:(res) => {
                if(callback)
                    callback(res);
            }
        })
    }
}
